//
//  AllTurnSideViewController.m
//  SIqICalendar
//
//  Created by sunjiawen on 17/3/8.
//  Copyright © 2017年 sjw. All rights reserved.
//

#import "AllTurnSideViewController.h"
#import "SettingTurnNameViewController.h"
#import "LeftSideCell.h"
#import "UIViewController+LGSideMenuController.h"
#import <MessageUI/MFMailComposeViewController.h>
#import "JWVersionNewsViewController.h"
#import <StoreKit/SKStoreProductViewController.h>
#import "MBProgressHUD.h"
#import "JWHUD.h"
#import "UIView+Toast.h"
#import "JWRealmManager.h"
#import "JWCalendarModel.h"
#import "JWScheduleModel.h"

@interface AllTurnSideViewController ()<UITableViewDelegate,UITableViewDataSource,MFMailComposeViewControllerDelegate,SKStoreProductViewControllerDelegate>
@property(nonatomic, strong) UITableView        *tableView;
@property(nonatomic, strong) JWCalendarModel    *currentSelectedModel;
@property(nonatomic, strong) NSMutableArray     *dataSource;
@end

@implementation AllTurnSideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialData];
    
    [self createUI];
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:JWCalendarAfterCreatedOrUpdatedNotification object:nil];
}

- (void)initialData {
    self.currentSelectedModel = [[JWRealmManager defaultManager] queryCalendarDefault];
}

- (void)loadData {
    
    NSMutableArray *tContainer = [NSMutableArray array];
    RLMResults *results = [[JWRealmManager defaultManager] queryAllCalendar];
    
    for (JWCalendarModel *model in results) {
        [tContainer addObject:model];
    }
   
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:tContainer];
    
}

- (void)createUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGFloat leftMargin = 10.f;
    
    // 头部蓝色背景View
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    headerView.backgroundColor = MainBlueColor;
    [self.view addSubview:headerView];
    
    UILabel *currentDateLabel = [[UILabel alloc]init];
    currentDateLabel.backgroundColor = [UIColor clearColor];
    currentDateLabel.textColor = [UIColor whiteColor];
    currentDateLabel.font = [UIFont boldSystemFontOfSize:defaultFont + 5];
    currentDateLabel.textAlignment = NSTextAlignmentLeft;
    currentDateLabel.text = [[DateUtil dateUtilShareIntance] dateToDateStr:[NSDate date] withFormatter:@"yyyy年M月d日"];
    [headerView addSubview:currentDateLabel];
    
    [currentDateLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftMargin);
        make.centerY.equalTo(headerView.centerY).offset(10.f);
    }];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"btn_add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(createNewTurnCalendar) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:addBtn];
    
    [addBtn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(currentDateLabel.centerY);
        make.right.equalTo(self.view.right).offset(-leftMargin);
    }];
    
    // TableView
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame), self.view.frame.size.width, self.view.frame.size.height - headerView.frame.size.height - WGiveHeight(35)) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.tableView];
    UIView *footerBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    
    UILabel *labelText = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, footerBgView.frame.size.width - 17 ,30)];
    labelText.backgroundColor = [UIColor clearColor];
    labelText.text = @"侧滑可以编辑↗️";
    labelText.textAlignment = NSTextAlignmentRight;
    labelText.textColor = [UIColor lightGrayColor];
    labelText.font = [UIFont systemFontOfSize:defaultFont - 2];
    [footerBgView addSubview:labelText];
    
    self.tableView.tableFooterView = footerBgView;
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - WGiveHeight(35), self.view.frame.size.width, WGiveHeight(35))];
    UIBarButtonItem *pingfenItem = [[UIBarButtonItem alloc]initWithTitle:@"评分支持" style:UIBarButtonItemStylePlain target:self action:@selector(goToPingfen)];
    UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *lianxiwo = [[UIBarButtonItem alloc]initWithTitle:@"联系开发者" style:UIBarButtonItemStylePlain target:self action:@selector(contactMe:)];
    UIBarButtonItem *gonggao = [[UIBarButtonItem alloc]initWithTitle:@"版本公告" style:UIBarButtonItemStylePlain target:self action:@selector(lookNews)];
    
    toolbar.items = @[pingfenItem,flexible,lianxiwo,flexible,gonggao];
    [self.view addSubview:toolbar];
    
}

- (void)lookNews {
    self.modalPresentationStyle = UIModalPresentationCustom;
    JWVersionNewsViewController *vc = [[JWVersionNewsViewController alloc]initWithNibName:@"JWVersionNewsViewController" bundle:nil];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)goToPingfen {

    NSString *appId = @"1221186861";
    
    // 创建对象
    SKStoreProductViewController *storeVC = [[SKStoreProductViewController alloc] init];
    // 设置代理
    storeVC.delegate = self;
    // 初始化参数
    NSDictionary *dict = [NSDictionary dictionaryWithObject:appId forKey:SKStoreProductParameterITunesItemIdentifier];
    
    // 跳转App Store页
    [JWHUD showGlobalProgressHUDWithTitle:@"请稍后" inView:[UIApplication sharedApplication].keyWindow];
    [storeVC loadProductWithParameters:dict completionBlock:^(BOOL result, NSError * _Nullable error) {
        [JWHUD dismissGlobalHUDInView:[UIApplication sharedApplication].keyWindow];

        if (error) {
            NSString *nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",appId];

            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen]];

        } else{
            // 弹出模态视图
            [self presentViewController:storeVC animated:YES completion:nil];
        }
    }];
}


#pragma mark -- SKStoreProductViewControllerDelegate
/**
 SKStoreProductViewControllerDelegate 方法，选择完成之后的处理
 
 @param viewController SKStoreProductViewController
 */
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
{
    NSLog(@"将要退出 App Store 页面了");
    [viewController dismissViewControllerAnimated:YES completion:^{
        NSLog(@"已经退出 App Store 页面完成了");
    }];
}

- (void)contactMe:(UIBarButtonItem *)sender {
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        NSLog(@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替");
        [self alertAction:@"当前系统版本不支持应用内发送邮件功能，可以将您的意见手动发送邮箱至\n 848303166@qq.com\n 或者添加邮箱的QQ号联系我"];
        return;
    }
    
    if (![mailClass canSendMail]) {
        
        NSLog(@"用户没有设置邮件账户");
        [self alertAction:@"您手机当前没有设置邮件账户，可以将您的意见手动发送邮箱至\n 848303166@qq.com\n 或者添加邮箱的QQ号联系我"];
        return;
    }
    
    MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];///创建视图控制器
    controller.mailComposeDelegate = self;
    [controller setToRecipients:[NSArray arrayWithObjects:@"sunjws686@gmail.com", @"848303166@qq.com", nil]];// 设置收件人，可以设置多人
    [controller setSubject:@"意见反馈"];//设置主题
    [controller setMessageBody:@"您的意见：" isHTML:NO];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)alertAction:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *copy = [UIAlertAction actionWithTitle:@"复制QQ号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
        
        pasteboard.string = @"848303166";
        
         [[UIApplication sharedApplication].keyWindow makeToast:@"QQ号已经复制到剪切板"];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
    
    [alertController addAction:copy];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 创建倒班表
/**
 创建倒班表
 */
- (void)createNewTurnCalendar {
//    [self.sideMenuController hideLeftViewAnimated:YES completionHandler:nil];
    
    SettingTurnNameViewController *vc = [[SettingTurnNameViewController alloc]init];
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
    
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        tableView.tableFooterView.hidden = NO;
        LeftSideCell *cell = [LeftSideCell cellWithTableView:tableView];
        JWCalendarModel *model = [self.dataSource objectAtIndex:indexPath.row];
        if (model) {
            if (model.isDefault.boolValue == YES) {
                cell.isdefaultIcon.hidden = NO;
            }else {
                cell.isdefaultIcon.hidden = YES;
            }
            
            if (model.calendarId == self.currentSelectedModel.calendarId) {
                // 当前选中的班组
                cell.backgroundColor = [UIColor emeraldColor];
                cell.textLabel.textColor = [UIColor whiteColor];
            }else {
                cell.backgroundColor = [UIColor clearColor];
                cell.textLabel.textColor = [UIColor blackColor];
            }
            
            cell.textLabel.text = model.calendarName;
            cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:16.f];
            
            NSDate *theDate = [NSDate date];
            NSInteger differDaysCount = -1;
            NSInteger theDateInDataSourceIndex = -1;
            NSInteger turnPeriod = model.scheduleStatus.count;
            NSDate *turnFirstDate = model.firstDate;
            
            if (turnFirstDate != nil && turnPeriod > 0) {
                differDaysCount = [[DateUtil dateUtilShareIntance] getDaysFrom:turnFirstDate To:theDate];
                theDateInDataSourceIndex = differDaysCount % turnPeriod;
            }
            // 获取串班信息
//            NSArray *exchangesData = [[DateUtil dateUtilShareIntance] getChangedDataByChangestr:model.exchangedDate];
//            JWScheduleModel *exchangeModel;
//            if (exchangesData) {
//                exchangeModel = [[DateUtil dateUtilShareIntance] judeThisDateIsExchanged:theDate andExchanges:exchangesData];
//            }
//
            if (differDaysCount >= 0) {
                JWScheduleModel *roundModel = model.scheduleStatus[theDateInDataSourceIndex];
//                if (exchangeModel != nil && ![roundModel.scheduleName isEqualToString:exchangeModel.scheduleName]) {
//                    cell.detailTextLabel.text = [NSString stringWithFormat:@"今天是%@班",exchangeModel.scheduleName];
//                    cell.detailTextLabel.textColor = exchangeModel.scheduleColor;
//                }else {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"今天是%@班",roundModel.scheduleName];
                    cell.detailTextLabel.textColor = roundModel.scheduleColor;
//                }
                
            }else {
//                if (exchangeModel != nil) {
//                    cell.detailTextLabel.text = [NSString stringWithFormat:@"今天是%@班",exchangeModel.scheduleName];
//                    cell.detailTextLabel.textColor = exchangeModel.scheduleColor;
//                }else {
                    cell.detailTextLabel.text = @"";
//                }
                
            }
        }

        return cell;
        
    
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count == 0) {
        return tableView.frame.size.height/2.0;
    }
    return WGiveHeight(50);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.dataSource.count > 0) {
        JWCalendarModel *model = [self.dataSource objectAtIndex:indexPath.row];
        self.currentSelectedModel = model;
        
        [PublicData sharedInstance].currentSelectedCalendarId = self.currentSelectedModel.calendarId;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JWCalendarListDidSelectedNotification object:nil];
        
        [self.tableView reloadData];
        
    }

}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  UITableViewCellEditingStyleDelete; // 要实现左滑删除的那一行的编辑风格必须是Delete风格
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 点击删除按钮调用的方法
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

{
    JWCalendarModel *model = [self.dataSource objectAtIndex:indexPath.row];
    // 编辑
    UITableViewRowAction *editBtn = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"编辑" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
//        [self.sideMenuController hideLeftViewAnimated:YES completionHandler:nil];
        
        SettingTurnNameViewController *vc = [[SettingTurnNameViewController alloc]init];
        vc.calendarModel = model;
        vc.isEdit = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
        [tableView setEditing:NO animated:YES];
    }];

    editBtn.backgroundColor = [UIColor orchidColor];
    
    // 删除
    UITableViewRowAction *deleteBtn = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [tableView setEditing:NO animated:YES];

        [[JWRealmManager defaultManager] deleteCalendarWithCalendarId:model.calendarId];
        [self.dataSource removeObject:model];
        
        if (model.calendarId == self.currentSelectedModel.calendarId) {
            
            // 当前被选中的日历被删除了，则从剩下的数据中选取第一位为当前选择的
            if (self.dataSource.count > 0) {
                self.currentSelectedModel = [self.dataSource firstObject];
                [PublicData sharedInstance].currentSelectedCalendarId = self.currentSelectedModel.calendarId;
            }else {
                self.currentSelectedModel = nil;
                [PublicData sharedInstance].currentSelectedCalendarId = @"";
            }
        }
        
        if (model.isDefault.boolValue == YES) {
            // 当前默认的日历被删除了，则从剩下的数据中选取第一位为默认的日历
            if (self.dataSource.count > 0) {
                JWCalendarModel *tmodel = [self.dataSource firstObject];
                [tmodel updateIsDefault:@YES];
            }
            
            // 更新wid组件
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JWCalendarAfterCreatedOrUpdatedNotification object:nil];
    }];
    
    // 设为默认
    deleteBtn.backgroundColor = [UIColor coolPurpleColor];
    UITableViewRowAction *setDefault = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"设为默认" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        [tableView setEditing:NO animated:YES];
        
        if (model.isDefault.boolValue == YES) return;
        
        [model updateIsDefault:@YES];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JWCalendarAfterCreatedOrUpdatedNotification object:nil];
    }];
    
    setDefault.backgroundColor = [UIColor burntOrangeColor];
    
    
    return @[deleteBtn,editBtn,setDefault];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)mailComposeController: (MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error;
{
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"用户点击发送，将邮件放到队列中，还没发送";
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            break;
        default:
            msg = @"";
            break;
    }
    NSLog(@"msg");
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
